import { createRouter, createWebHistory } from 'vue-router'
// 导入userStore
import { useUserStore } from '@/store/user'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: () => import('@/views/Login.vue') },
    // 添加智能交通监控页面路由
    { 
      path: '/index', 
      name: 'Index',
      component: () => import('@/views/index.vue'),
      meta: { requiresAuth: true, title: '智能交通监控' }
    },
    // 或者你也可以设置为根路径的默认页面
    // { path: '/', component: () => import('@/views/index.vue'), meta: { requiresAuth: true, title: '智能交通监控' } },
    { 
      path: '/home', 
      component: () => import('@/views/Home.vue'),
      meta: { requiresAuth: true, title: '首页' }
    },
    { path: '/register', name: 'Register', component: () => import('@/views/Register.vue'), meta: { requiresAuth: false } },
    { path: '/violation', name: 'Violation', component: () => import('@/views/Violation.vue'), meta: { requiresAuth: true, title: '违法记录', roles: ['admin', 'superadmin'] } },
    { path: '/alert', name: 'Alert', component: () => import('@/views/Alert.vue'), meta: { requiresAuth: true, title: '预警中心', roles: ['admin', 'superadmin'] } },
    { path: '/upload', name: 'Upload', component: () => import('@/views/Upload.vue'), meta: { requiresAuth: true, title: '视频上传', roles: ['admin', 'superadmin'] } },
    { path: '/enforcement', name: 'Enforcement', component: () => import('@/views/Enforcement.vue'), meta: { requiresAuth: true, title: '执法处理', roles: ['admin', 'superadmin'] } },
    {
      path: '/profile',
      component: () => import('@/views/Profile.vue'),
      meta: { requiresAuth: true, title: '个人信息' }
    },
    {
      path: '/appeal',
      name: 'Appeal',
      component: () => import('@/views/Appeal.vue'),
      meta: { requiresAuth: true, title: '申诉管理' }
    },
    {
      path: '/user-management',
      name: 'UserManagement',
      component: () => import('@/views/UserManagement.vue'),
      meta: { requiresAuth: true, title: '用户管理', roles: ['admin', 'superadmin'] }
    },
    {
      path: '/my-violations',
      name: 'MyViolations',
      component: () => import('@/views/MyViolations.vue'),
      meta: { requiresAuth: true, title: '我的违法记录' }
    },
    {
      path: '/workspace',
      name: 'Workspace',
      component: () => import('@/views/Workspace.vue'),
      meta: { requiresAuth: true, title: '工作台' }
    },
    {
      path: '/illegal-upload',
      name: 'IllegalUpload',
      component: () => import('@/views/IllegalUpload.vue'),
      meta: { requiresAuth: true, roles: ['admin', 'superadmin'], title: '违法记录上传' }
    },
    { path: '/:pathMatch(.*)*', redirect: '/login' }
  ]
})

router.beforeEach((to, from, next) => {
  const userStore = useUserStore() // 初始化userStore实例
  console.log('路由守卫检查:', {to, hasToken: !!userStore.token, userRole: userStore.userInfo?.role})
  
  // 检查是否需要登录
  if (to.meta.requiresAuth && !userStore.token) {
    next('/login')
    return
  } 
  
  // 已登录用户访问登录页，重定向到首页
  if (to.path === '/login' && userStore.token) {
    next('/home')
    return
  }
  
  // 检查角色权限
  if (to.meta.roles && to.meta.roles.length > 0) {
    const userRole = userStore.userInfo?.role
    let hasPermission = false
    
    // 角色映射
    const roleMap = {
      '0': 'user',     // 普通用户
      '1': 'admin',    // 管理员
      '2': 'superadmin', // 系统管理员
      // 添加数字类型的映射
      0: 'user',
      1: 'admin',
      2: 'superadmin'
    }
    
    const mappedRole = roleMap[userRole] || 'user'
    
    // 检查用户角色是否在允许的角色列表中
    if (to.meta.roles.includes(mappedRole)) {
      hasPermission = true
    }
    
    if (!hasPermission) {
      console.warn('用户无权限访问该页面:', to.path, '用户角色:', mappedRole)
      next(from.fullPath || '/home') // 无权限时重定向到访问前的页面，若无可选页面则跳转至首页
      return
    }
  }
  
  // 通过所有检查，允许访问
  next()
})

export default router